package info.niwota.web.jetty;

import info.niwota.commons.io.Files;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.HttpGenerator;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.security.SslSocketConnector;
import org.mortbay.thread.QueuedThreadPool;

import android.content.Context;

public class JettyServer {
	private Context ctx = null;
	private Server server = null;

	private int maxThreads = 32;
	private final boolean enableSsl = false;
	private Connector connector;
	
	public int getLocalPort() {
		return (connector == null ? -1 : connector.getLocalPort());
	}
	
	private void configureConnectors() {
		
		connector = new SocketConnector();
		connector.setPort(0);
		
		server.addConnector(connector);
		//
		if (enableSsl ) {
			SslSocketConnector sslConnector = new SslSocketConnector();
			sslConnector.setPort(0);
			sslConnector.setKeystore(null);
			sslConnector.setKeystoreType("bks");
			server.addConnector(sslConnector);
		}
	}

	private void configureHandlers() {
		Handler handler = new HttpAdapter(ctx);
		server.setHandler(handler);
	}

	private void configureSettings() {
		System.setProperty("org.mortbay.log.class",
				"info.niwota.web.jetty.AndroidLog");
		org.mortbay.log.Log.setLog(new AndroidLog());
		// Set jetty.home
		java.io.File jhome = Files.getSubDir(ctx, "jetty");
		if (!jhome.exists()) {
			jhome.mkdirs();
		}
		System.setProperty("jetty.home", jhome.getPath());
	}

	private void configureThreadPool() {
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMaxThreads(maxThreads);
		server.setThreadPool(threadPool);
	}

	public void init(Context ctx) {
		this.ctx = ctx;
	}

	public boolean isRunning() {
		return (server != null && server.isRunning());
	}

	public void shutdown() throws Exception {
		server.stop();
		//server.join();
		server = null;
	}

	public void startup() throws Exception {
		server = new Server();
		//
		configureSettings();
		configureThreadPool();
		//
		configureConnectors();
		configureHandlers();
		//
		server.start();
		//
		HttpGenerator.setServerVersion("1.0.0");
	}
}
